#include<iostream>
#include<unistd.h>
#include<pthread.h>
using std::endl;
using std::cout;
int tickets=10000;
void* Buyticket(void* argc)
{
    const char* name=static_cast<const char*>(argc);
    while(true)
    {
        if(tickets>0)
        {
            usleep(100);
            printf("%s:%lu Get ticket:%d!\n",name,pthread_self(),tickets--);
            usleep(100);
        }
        else{
            printf("%s::%lu There is no ticket!\n",name,pthread_self());
            break;
        }
    }
    return nullptr;
}
int main()
{
    pthread_t tid1,tid2,tid3,tid4;
    pthread_create(&tid1,nullptr,Buyticket,(void*)"Thread 1");
    pthread_create(&tid2,nullptr,Buyticket,(void*)"Thread 2");
    pthread_create(&tid3,nullptr,Buyticket,(void*)"Thread 3");
    pthread_create(&tid4,nullptr,Buyticket,(void*)"Thread 4");
    
    pthread_join(tid1,nullptr);
    cout<<"Main thread has joined thread 1!"<<endl;
    pthread_join(tid2,nullptr);
    cout<<"Main thread has joined thread 2!"<<endl;
    pthread_join(tid3,nullptr);
    cout<<"Main thread has joined thread 3!"<<endl;
    pthread_join(tid4,nullptr);
    cout<<"Main thread has joined thread 4!"<<endl;
    return 0;
}
